<template>
  <CustomDialog ref="customDialog" width="600px" :title="dialogProps.title" :isView="dialogProps.isView"
    :onSubmit="handleSubmit" :onClose="handleClose">
    <template #header>
      {{ `${dialogProps.title}组织架构` }}
    </template>
    <template #content>
      <el-form ref="ruleFormRef" label-width="120px" label-suffix=" :" :rules="rules" :disabled="dialogProps.isView"
        :model="dialogProps.row" :hide-required-asterisk="dialogProps.isView">
        <el-form-item label="上级组织架构" prop="parentDepartmentId">
          <el-tree-select v-model="dialogProps.row.parentDepartmentId" :data="dialogProps.allData" filterable
            check-strictly />
        </el-form-item>
        <el-form-item label="组织架构名称" prop="departmentName">
          <BInput v-model="dialogProps.row.departmentName" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="customDialog?.acceptParams(false)">取消</el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </CustomDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import CustomDialog from "@/components/Dialog/CustomDialog.vue";
import BInput from "@/components/BaseComponents/BInput.vue";

const rules = reactive({
  parentDepartmentId: [{ required: true, message: "请选择上级组织架构" }],
  departmentName: [{ required: true, message: "请输入组织架构名称" }]
});

interface DialogProps {
  title: string;
  isView: boolean;
  row: any;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  allData?: any
}

const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {},
  allData: []
});

const customDialog = ref<InstanceType<typeof CustomDialog>>();
//转换为树形结构
const convertToTreeSelectData = (data: any): any[] => {
  return data.map(node => {
    const treeSelectNode: any = {
      value: node.id,
      label: node.departmentName,
      children: node.children ? convertToTreeSelectData(node.children) : undefined
    };
    return treeSelectNode;
  });
}


// 接收父组件传过来的参数
const acceptParams = async (params: DialogProps) => {
  //修改，使新增时数据不清除
  dialogProps.value.api = params.api;
  dialogProps.value.getTableList = params.getTableList;
  dialogProps.value.title = params.title;
  dialogProps.value.isView = params.isView;
  dialogProps.value.allData = convertToTreeSelectData(params.allData);

  if (params.title === '新增') {
    dialogProps.value.row.parentDepartmentId = params.row.id
  } else {
    dialogProps.value.row = Object.assign({}, params.row);
  }

  customDialog.value?.acceptParams(true);
};


// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    // 将角色名称转换为角色 ID
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}组织架构成功！` });
      customDialog.value?.acceptParams(false);
      dialogProps.value.getTableList!();
    } catch (error) {
      console.log(error);
    }
  });
};

const handleClose = () => {
  customDialog.value?.acceptParams(false);
};

defineExpose({
  acceptParams
});
</script>
